function flush() {
    $("#data-body").html("");
    chrome.storage.sync.get({alireviews:{}}, function(items) {
        let item = items['alireviews'];
        let number = 0;
        for (let i in item) {
            let data = item[i];
            if (!data) {
                continue;
            }

            let html = "<tr>"
            number++;
            html += '<td>' + i + '</td>';
            html += '<td>' + data.username + '</td>';
            html += '<td>' + data.country + '</td>';
            html += '<td>' + data.content + '</td>';
            html += '<td>' + data.time + '</td>';
    
            
            html += '<td>';
            if (data.img) {
                let photos = data.img.split(',');
                for (let j = 0; j < photos.length; j++) {
                    if (photos) {
                        html += "<img src='" + photos[j] + "' style='max-width: 60px;max-height: 60px;margin-right: 5px;'/>"
                    }
                }
            }
    
            html += '</td>';
            html += '<td><button type="button" class="btn btn-danger btn-sm" data-item-id="' + i + '" data-button-type="del">Del</button></td></tr>'
            $("#data-body").append(html);
        }
        $("#message").html("<b>Has " + number + " items!</b>")
    });
}

function deleteItem(id) {
    chrome.storage.sync.get({alireviews:{}}, function(items) {
        let item = items['alireviews'];
        let exist = false;
        for (let i in item) {
            if (i == id) {
                item[i] = null;
                exist = true;
            }
        }
        chrome.storage.sync.set({alireviews: item}, function() {
            flush();
        });
    });
}

// document.getElementById("flushButton").addEventListener("click", flush);
document.addEventListener('click', function(e) {
    let target = e.target;
    if (target.dataset.buttonType == 'flush') {
        flush();
    }
    if (target.dataset.buttonType == 'del') {
        deleteItem(target.dataset.itemId);
    }
});
flush();